package proxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * @Author: Yangu
 * @Created time: 2021/1/4 14:31
 * @Description :
 */
public class UserProxy implements InvocationHandler {

    private Object target;

    public Object getInstance(Object target) {
        this.target = target;
        Class<?> clazz = target.getClass();
        return Proxy.newProxyInstance(clazz.getClassLoader(), clazz.getInterfaces(), this);
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        before();
        Object obj = method.invoke(this.target, args);
        after();
        return obj;
    }

    private void after() {
        System.out.println("after invoke");
    }

    private void before() {
        System.out.println("before invoke");
    }

    public static void main(String[] args) {
        UserService userService = (UserService) new UserProxy().getInstance(new UserServiceImpl());
        userService.getUserName("xiaoming");
        userService.testFinal("aaaa");
        UserServiceImpl userServiceImpl = new UserServiceImpl();
        userServiceImpl.testFinalExtends();
    }
}
